import React, { memo, useState, useCallback } from 'react';
import { Divider, Tooltip, message, Modal, Icon, Form } from 'antd';
import { isSuccess } from '@/utils/request';
import { BUTTON } from '@/pages/SalaryManage/SalaryCalculate/constant/recheckButtonConstant';
import { CHECK_STATUS } from '@/pages/SalaryManage/constant/recheckConstant';

import { goToSalaryRecheckDataChart } from '@/pages/SalaryManage/utils/pageNavigateUtil';

import LimitInput from '@/components/LimitInput';

import useArticleWage from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHandle/components/useArticleWage';

import rejectStyles from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHandle/index.less';

const RejectModal = Form.create()(({ form, record, organizationCode, updateViewFn, cancelFn, reject }) => {
    //  弹窗=》确定按钮是否加载状态
    const [confirmLoad, setConfirmLoad] = useState(false);

    const { getFieldDecorator } = form;

    // 弹窗确定按钮
    const modelOk = useCallback(async () => {
        form.validateFields(async (errors, value) => {
            setConfirmLoad(true);
            const rejectRes = await reject({
                salaryPayrollId: record.id,
                organizationCode,
                year: record.yearMonth.substr(0, 4),
                month: record.yearMonth.substr(5),
                ...value
            });
            if (isSuccess(rejectRes)) {
                updateViewFn(rejectRes);
                cancelFn();
            } else {
                message.error(rejectRes.msg);
            }
        });
    }, [cancelFn, form, organizationCode, record.id, record.yearMonth, reject, updateViewFn]);

    return (
        <>
            <Modal
                title="驳回"
                visible
                onOk={modelOk}
                onCancel={cancelFn}
                destroyOnClose
                centered
                confirmLoading={confirmLoad}
            >
                <div className={rejectStyles.msg}>
                    <Icon type="exclamation-circle" theme="filled" />
                    将驳回{record.employeeName}的薪资，请确认
                </div>
                <Form layout="inline" className={rejectStyles.recheckForm}>
                    <Form.Item label="驳回备注">
                        {getFieldDecorator('remark')(
                            <LimitInput rows={4} cols={45} maxLength={200} area showNumber placeholder="请输入" />
                        )}
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
});

const OperateCell = props => {
    const { record, updateViewFn, organizationCode, reject, cancelCheck, passCheck } = props;

    const { openArticleModal, render: articleRender } = useArticleWage(updateViewFn, {
        year: record.yearMonth?.substr(0, 4),
        month: record.yearMonth?.substr(5),
        organizationCode
    });

    const handleFn = res => {
        if (res && res.code === 10000 && res.data && res.data.responseCode) {
            openArticleModal(res.data.msg, res.data.responseCode === 10000);
            return;
        }
        message.success(res.message || '操作成功');
        updateViewFn();
    };

    //  驳回弹窗
    const [visible, setVisible] = useState(false);
    // 驳回
    const showRejectModal = prop => {
        if (prop.disabled) {
            return;
        }
        setVisible(true);
    };

    // 取消复核
    const cancelCheckFn = async prop => {
        if (prop.disabled) {
            return;
        }
        const cancelRes = await cancelCheck({
            salaryPayrollId: record.id,
            year: record.yearMonth.substr(0, 4),
            month: record.yearMonth.substr(5),
            organizationCode
        });
        if (isSuccess(cancelRes)) {
            handleFn(cancelRes);
        } else {
            message.error(cancelRes.msg);
        }
    };

    // 复核通过
    const passCheckFn = async prop => {
        if (prop.disabled) {
            return;
        }
        const passRes = await passCheck({
            salaryPayrollId: record.id,
            year: record.yearMonth.substr(0, 4),
            month: record.yearMonth.substr(5),
            organizationCode
        });
        if (isSuccess(passRes)) {
            handleFn(passRes);
        } else {
            message.error(passRes.msg);
        }
    };

    const goToDataDetail = useCallback(() => {
        goToSalaryRecheckDataChart({
            employeeCode: record.employeeCode,
            yearMonth: record.yearMonth,
            organizationCode
        });
    }, [organizationCode, record.employeeCode, record.yearMonth]);
    const btnArray = [];
    const buttons = record.buttons || [];

    buttons.forEach(button => {
        if (BUTTON.HR_REJECT === button.code || BUTTON.FN_REJECT === button.code) {
            btnArray.push({
                name: '驳回',
                fontClass: 'status_reject iconlistfunction_reject_icon_default',
                onClick: showRejectModal,
                disabled: button.disabled,
                prop: button
            });
        }

        if (BUTTON.DATA_DETAIL === button.code || BUTTON.FINAL_DATA_DETAIL === button.code) {
            btnArray.push({
                name: '数据详情',
                fontClass: 'status_cancel iconshujuxiangqing',
                onClick: goToDataDetail,
                disabled: button.disabled,
                prop: button
            });
        }

        if (
            (BUTTON.HR_CANCEL_CHECK === button.code && CHECK_STATUS.CHECKED.code === record.hrCheckStatus) ||
            (BUTTON.FN_CANCEL_CHECK === button.code && CHECK_STATUS.CHECKED.code === record.financeCheckStatus)
        ) {
            btnArray.push({
                name: '取消复核',
                fontClass: 'status_cancel iconlistfunction_auditcanceled_icon_default',
                onClick: cancelCheckFn,
                disabled: button.disabled,
                prop: button
            });
        }

        if (
            (BUTTON.HR_PASS_CHECK === button.code && CHECK_STATUS.CHECKED.code !== record.hrCheckStatus) ||
            (BUTTON.FN_PASS_CHECK === button.code && CHECK_STATUS.CHECKED.code !== record.financeCheckStatus)
        ) {
            btnArray.push({
                name: '复核通过',
                fontClass: 'status_approve iconlistfunction_auditpassed_icon_default',
                onClick: passCheckFn,
                disabled: button.disabled,
                prop: button
            });
        }
    });

    return (
        <div>
            {btnArray.map((item, index, arr) => (
                <React.Fragment key={item.name || index}>
                    <Tooltip title={item.name}>
                        <i
                            className={['iconfont', item.fontClass, { p_status_disable: item.disabled }]}
                            onClick={() => item.onClick(item)}
                        />
                    </Tooltip>
                    {index + 1 < arr.length ? <Divider type="vertical" /> : null}
                </React.Fragment>
            ))}
            {visible ? (
                <RejectModal
                    record={record}
                    reject={reject}
                    updateViewFn={handleFn}
                    organizationCode={organizationCode}
                    cancelFn={() => setVisible(false)}
                />
            ) : null}
            {articleRender()}
        </div>
    );
};

export default memo(OperateCell);
